<template>
  <div class="step-two">
    <reservePlan :plan="routeParam" />

    <div class="main">
      <el-card style="width: 30%; margin-right: 20px">
        <h2 style="text-align: center">优化策略</h2>
        <div
          v-for="({ strategyName, description }, i) in strateData"
          :key="i"
          v-loading="loading"
          class="list-item"
          @click="watchDetails(i)"
        >
          <el-card
            style="height: 150px"
            :style="{
              'background-color': checkList[i] ? '#DCF3FD' : '#fff',
            }"
          >
            <div class="item-title">{{ strategyName }}</div>
            <div class="item-scene">{{ description }}</div>
            <!-- <div v-if="dispatcher" class="item-dispatcher">所属调度员： {{ dispatcher }}</div> -->
            <el-button
              type="primary"
              class="item-btn"
              @click="watchMore(i)"
            >更多</el-button>
            <el-checkbox v-model="checkList[i]" class="item-check" @change="watchDetails(i)" />
          </el-card>
        </div>
      </el-card>

      <el-card style="width: 40%; margin-right: 20px;height: 620px;overflow-y: scroll;">
        <h2 style="text-align: center">优化模型列表</h2>
        <div
          v-for="(item, i) in modelList"
          :key="i"
          v-loading="loading1"
          class="list-item"
          :draggable="true"
          @dragstart="dragstart(item)"
          @dragenter="dragenter(item,$event)"
          @dragend="dragend(item,$event)"
          @dragover="dragover($event)"
          @click="checkModel(i)"
        >
          <el-card style="height: 150px; background-color: #dcf3fd">
            <div class="item-title">{{ item.modelName }}</div>
            <h5>{{ item.description }}</h5>
            <el-checkbox
              v-model="checkModelList[i]"
              disabled
              class="item-check"
            />
          </el-card>
        </div>
      </el-card>
      <el-card v-if="type !== '2'" style="width: 30%">
        <h2 style="text-align: center">参数列表</h2>
        <div
          v-for="{ cname, name } in paramsData"
          :key="name"
          style="display: flex"
        >
          <span
            style="
              width: 150px;
              text-align: right;
              margin: 5px;
              font-size: 17px;
            "
          >{{ cname }}:</span>
          <el-input
            v-model="params[name]"
            style="flex: 1; margin: 5px"
            type="text"
          />
        </div>
        <div class="param-btn">
          <el-button type="primary" @click="keepParam">保存</el-button>
          <el-button type="success" @click="resetParam">重值</el-button>
        </div>
      </el-card>
      <el-card v-else style="width: 30%">
        <h2 style="text-align: center">优化策略分配列表</h2>
        <div style="display: flex">
          <span style="width: 100px; margin-top: 9px">调度员：</span>
          <el-input v-model="userName" suffix-icon="el-icon-search" />
        </div>
        <ul class="user-list">
          <li v-for="(item, i) in userList" :key="item.userId" style="">
            <el-checkbox
              v-model="userChecked[i]"
              @change="chooseUser(i)"
            /><span>{{ item.userName }}</span>
          </li>
        </ul>
      </el-card>
    </div>
    <div class="btn-group">
      <el-button style="width: 300px" @click="goUp">上一步</el-button>
      <el-button
        v-if="type !== '2'"
        type="primary"
        style="width: 300px"
        @click="goNext"
      >下一步</el-button>
      <el-button
        v-else
        type="success"
        style="width: 300px"
        @click="issue"
      >立即下发</el-button>
    </div>
  </div>
</template>
<script>
import { deepClone } from '@/utils/index'
import { listUser } from '@/api/system/user'
import { usertaskstrategy, strategyTask } from '@/api/decision/task'
import reservePlan from '@/components/createPlan/reservePlan'
import { modelParam, keepModel } from '@/api/decision/model'
import { listStrategy, listModel } from '@/api/decision/strategy'
export default {
  components: {
    reservePlan: reservePlan
  },
  data() {
    return {
      planName: '海运封航',
      open: false,
      loading: false,
      loading1: false,
      checkList: [],
      strateDataList: [],
      modelList: [],
      checkModelList: [],
      strategyId: '', // 当前选择的策略id
      modelCheck: null,
      routeParam: null,
      type: '1', // 1是主班配置 2是指派
      paramsData: [],
      params: {},
      modelId: '',
      userList: [],
      userChecked: [],
      userName: '',
      oldData: null, // 开始排序时按住的旧数据
      newData: null, // 拖拽过程的数据
      userId: '' // 指派人id
    }
  },
  computed: {
    strateData() {
      return this.strateDataList
    },
    userID() {
      return this.$store.state.user.userId
    }
  },
  created() {
    this.type = this.$route.query.id
    if (this.type === '2') {
      this.getUser()
    }
    const planParam = JSON.parse(localStorage.getItem('planParam'))
    if (planParam) {
      this.routeParam = planParam
      if (this.routeParam.taskState !== '2' && this.type === '3') {
        this.getStrategyTask(this.routeParam.taskId)
      } else {
        this.getListStrategy()
      }
    }
  },
  methods: {
    dragstart(value) {
      this.oldData = value
    },

    // 记录移动过程中信息
    dragenter(value, e) {
      this.newData = value
      e.preventDefault()
    },

    // 拖拽最终操作
    dragend(value, e) {
      if (this.oldData !== this.newData) {
        const oldIndex = this.modelList.indexOf(this.oldData)
        const newIndex = this.modelList.indexOf(this.newData)
        const newItems = [...this.modelList]
        // 删除老的节点
        newItems.splice(oldIndex, 1)
        // 在列表中目标位置增加新的节点
        newItems.splice(newIndex, 0, this.oldData)
        this.modelList = [...newItems]
      }
    },

    // 拖动事件（主要是为了拖动时鼠标光标不变为禁止）
    dragover(e) {
      e.preventDefault()
    },
    // 选中策略列表，弹出模型列表
    getModelList(id) {
      this.strategyId = id
      this.loading1 = true
      this.checkModelList = []
      listModel(id).then((response) => {
        this.modelList = response.rows
        this.modelList.forEach((element) => {
          this.checkModelList.push(true)
        })
        this.total = response.total
        this.loading1 = false
      })
    },
    /**
     * 根据预案查询下面的策略id
     */
    getStrategyTask(taskId) {
      this.loading1 = true
      this.checkList = []
      strategyTask(taskId).then((response) => {
        this.strateDataList = response.rows
        if (this.strateDataList.length === 0) {
          this.getListStrategy()
        } else {
          this.strateDataList.forEach((element) => {
            this.checkList.push(true)
          })
          this.getModelList(this.strateDataList[0].strategyId)
          this.total = response.total
          this.loading1 = false
        }
      })
    },
    // 获取用户
    getUser() {
      listUser(this.userName).then((response) => {
        this.userList = response.rows
        this.total = response.total
        this.userList.forEach((element) => {
          this.userChecked.push(false)
        })
      })
    },
    // 选择指派人
    chooseUser(i) {
      for (let i = 0; i < this.userChecked.length; i++) {
        this.userChecked[i] = false
      }
      this.userChecked[i] = true
      this.userId = this.userList[i].userId
    },
    // 立即下发
    issue() {
      const param = {}
      const arr = []
      this.checkList.forEach((item, i) => {
        if (item) {
          arr.push(this.strateDataList[i].strategyId)
        }
      })
      param['userId'] = this.userId
      param['taskId'] = this.routeParam.taskId
      param['strategyIds'] = arr
      usertaskstrategy(param).then((response) => {
        this.$router.push('/decision/plan/task')
      })
    },
    // 选中模型列表，弹出模型参数列表
    getModelParam(id) {
      // this.loading = true
      const param = {
        taskId: this.routeParam.taskId,
        strategyId: this.strategyId,
        modelId: id
      }
      modelParam(param).then((response) => {
        this.paramsData = response.data
        if (this.paramsData) {
          this.paramsData.forEach((item) => {
            this.$set(this.params, item.name, item.value)
          })
        }
      })
    },
    // 获取所有策略
    getListStrategy() {
      this.loading1 = true
      listStrategy(this.queryParams).then((response) => {
        this.strateDataList = response.rows
        this.strateDataList.forEach((element) => {
          this.checkList.push(false)
        })
        this.total = response.total
        this.loading1 = false
      })
    },
    resetParam() {
      // this.paramsData = []
      this.params = {}
      this.paramsData.forEach((item) => {
        this.$set(this.params, item.name, item.value)
      })
    },
    watchDetails(i) {
      const data = deepClone(this.strateDataList)
      // event.stopPropagation()
      this.checkList[i] = !this.checkList[i]
      this.strateDataList = data
      if (this.checkList[i]) {
        this.getModelList(this.strateDataList[i].strategyId)
      }
    },
    // 查看更多
    watchMore() {

    },
    checkModel(i) {
      this.checkModelList[i] = true
      this.modelId = this.modelList[i].modelId
      this.getModelParam(this.modelId)
    },
    keepParam() {
      const param = {}
      param['strategyId'] = this.strategyId
      param['modelId'] = this.modelId
      param['taskId'] = this.routeParam.taskId

      const data = []
      for (const key in this.params) {
        const item = {}
        item['name'] = key
        item['value'] = this.params[key]
        item['cname'] = this.paramsData.filter((a) => {
          return a.name === key
        })[0].cname
        data.push(item)
      }

      param['modelJson'] = JSON.stringify(data)

      keepModel(param).then((response) => {
        if (response.code === 200) {
          this.$message.success('保存成功')
        } else {
          this.$message.error(response.msg)
        }
      })
    },
    goUp() {
      this.$router.go(-1)
    },
    goNext() {
      const param = {}
      const arr = []
      this.checkList.forEach((item, i) => {
        if (item) {
          arr.push(this.strateDataList[i].strategyId)
        }
      })
      sessionStorage.setItem('strategyIds',JSON.stringify(arr))
      param['userId'] = this.userID
      param['taskId'] = this.routeParam.taskId
      param['strategyIds'] = arr
      usertaskstrategy(param).then((response) => {
        // this.router.push('/decision/plan/task')
        this.$router.push({ path: '3' })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.step-two {
  padding: 0px 15px;
  width: 100%;
}

.main {
  margin-top: 15px;
  display: flex;
  width: 100%;
  .list-item {
    position: relative;
    cursor: pointer;
    width: 98%;
    margin-bottom: 20px;
    .item-check {
      position: absolute;
      right: 10px;
      top: 10px;
    }
    .item-title {
      font-size: 18px;
      font-weight: 600;
    }
    .item-scene {
      margin: 10px 0;
    }
    .item-btn {
      position: absolute;
      right: 10px;
      bottom: 10px;
    }
    .active {
      background: rgb(76, 190, 110);
    }
  }
  .param-btn {
    margin-top: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .user-list {
    li {
      margin-bottom: 10px;
      list-style: none;
      span {
        margin-left: 10px;
      }
    }
  }
}
.btn-group {
  display: flex;
  margin-top: 15px;
  justify-content: center;
}
</style>
